package com.relife.core.service;

import java.util.Date;

import com.relife.common.utils.DateUtil;
import com.relife.core.entity.SerialEntity;
import com.relife.core.qbc.QbcQuery;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service
@Transactional
public class SerialService extends BaseService {

	/***
	 * 
	 * @author WU
	 * @date 2016年6月2日 下午2:50:51
	 * @param pix
	 * @param type
	 * @return
	 */
	public String hasCode(String pix, String type) {
		String code = DateUtil.getTime(DateUtil.YYYYMMDD);
		String addTime = DateUtil.getTime(type);
		QbcQuery qbc = new QbcQuery(SerialEntity.class);
		qbc.add(Restrictions.eq("codeType", pix));
		qbc.add(Restrictions.eq("addTime", addTime));
		SerialEntity initial = this.get(qbc);
		if (initial == null) {
			initial = new SerialEntity();
			initial.setCode(1);
			initial.setCodeType(pix);
			initial.setAddTime(addTime);
			this.save(initial);
		} else {
			initial.setCode(initial.getCode() + 1);
		}
		code = pix + code + String.format("%04d", initial.getCode());
		return code;
	}

	/***
	 * 
	 * @author WU
	 * @date 2017年8月29日 上午11:02:19
	 * @param codeType
	 * @return
	 */
	public Integer hasCode(String codeType) {
		SerialEntity initial = this.get(SerialEntity.class, "codeType", codeType);
		if (initial == null) {
			initial = new SerialEntity();
			initial.setCode(1);
			initial.setCodeType(codeType);
			this.save(initial);
		} else {
			initial.setCode(initial.getCode() + 1);
		}
		return initial.getCode();
	}

	public String hasDepartCode(String type) {
		QbcQuery qbc = new QbcQuery(SerialEntity.class);
		qbc.add(Restrictions.eq("codeType", type));
		SerialEntity initial = this.get(qbc);
		if (initial == null) {
			initial = new SerialEntity();
			initial.setCode(1);
			initial.setCodeType(type);
			initial.setAddTime(DateUtil.getTime(DateUtil.YYYYMMDD, new Date()));
			this.save(initial);
		} else {
			initial.setCode(initial.getCode() + 1);
		}
		return type + String.format("%02d", initial.getCode());
	}

}
